﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;

namespace Bundler
{
    [ExcludeFromCodeCoverage]
    internal class HttpHelper
    {
        public static HttpModel GetHttpModel()
        {
            var model = new HttpModel();

            model.IsDebuggingEnabled = HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled;

            return model;
        }

        public static string MapPath(string virutalPath)
        {
            if (HttpContext.Current != null)
            {
                return HostingEnvironment.MapPath(virutalPath);
            }

            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, virutalPath.Replace("~/","").Replace("/", "\\"));
        }

        public static string MakeRelative(string fromPath, string toPath)
        {
            if (HttpContext.Current != null)
            {
                return VirtualPathUtility.MakeRelative(fromPath, toPath);
            }

            var fromPathMapped = MapPath(fromPath).ToLower();
            var toPathMapped = MapPath(toPath).ToLower();
            var root = GetCommonStartingSubString(new[] {fromPathMapped, toPathMapped});
            if (!root.EndsWith("\\"))
            {
                root = root.Substring(0, root.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1);
            }
            var relativePath = toPathMapped.Substring(root.Length, toPathMapped.Length - root.Length);
            return relativePath.Replace("\\", "/");
        }

        public static string ToAbsolute(string virtualPath)
        {
            if(String.IsNullOrWhiteSpace(virtualPath))
                throw new ArgumentNullException("virtualPath");

            if (HttpContext.Current != null)
            {
                return VirtualPathUtility.ToAbsolute(virtualPath);
            }

            return virtualPath.Replace("~/", "/");
        }

        private static string GetCommonStartingSubString(string[] strings)
        {
            if (strings.Length == 0)
                return string.Empty;
            if (strings.Length == 1)
                return strings[0];
            var charIdx = 0;
            while (IsCommonChar(strings, charIdx))
                ++charIdx;
            return strings[0].Substring(0, charIdx);
        }
        private static bool IsCommonChar(IList<string> strings, int charIdx)
        {
            if (strings[0].Length <= charIdx)
                return false;

            for (var strIdx = 1; strIdx < strings.Count; ++strIdx)
            {
                if (strings[strIdx].Length <= charIdx || strings[strIdx][charIdx] != strings[0][charIdx])
                {
                    return false;
                }
            }
            return true;
        }
    }
}
